package topic;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import common.ContantsConfig;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.Connection;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;

import java.io.IOException;

/**
 * Created by Will.Zhang on 2017/2/15 0015 18:09.
 * 待删除
 */
public class TopicConsumer2 {

    public static void main(String[] args) throws IOException {
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory(ContantsConfig.MQ_HOST);
        connectionFactory.setUsername(ContantsConfig.USER);
        connectionFactory.setPassword(ContantsConfig.PASSWORD);

        Connection connection = connectionFactory.createConnection();
        //创建一个新的通道, 不支持事务, true表示支持
        Channel channel = connection.createChannel(false);


        /**
         *  声明交换器
         */
        channel.exchangeDeclare("log-exchange", BuiltinExchangeType.TOPIC, true, false, null);
        //声明3个交换器
        channel.queueDeclare("msg-inbox-errors", false, true, true, null);
        channel.queueDeclare("msg-inbox-logs", false, true, true, null);
        channel.queueDeclare("all-logs", false, true, true, null);

        channel.queueBind("msg-inbox-errors", "log-exchange", "error.msg-inbox");
        channel.queueBind("msg-inbox-logs", "log-exchange", "*.msg-inbox");
        channel.queueBind("all-logs", "log-exchange", "*");

        /**
         * 使用监听异步接收消息
         */
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory);
        container.addQueueNames("msg-inbox-errors", "msg-inbox-logs", "all-logs");
        container.setMessageListener(new MessageListener() {
            public void onMessage(Message message) {
                System.out.println(message);
            }
        });


        container.start();
    }
}
